package iscas.bridge.controller;

import iscas.bridge.entity.RequestData;
import iscas.bridge.entity.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/bridge")
public class RequestController {

    private static final Logger logger = LoggerFactory.getLogger(RequestController.class);

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/process")
    public ResponseData processRequest(@RequestBody RequestData requestData) {
        ResponseData responseData = new ResponseData();
        logger.info("收到处理请求，服务名称: {}，命名空间: {}", requestData.getServicename(), requestData.getNamespace());

        // 组织请求URL
        String originalUrl = requestData.getRequestDefine().getUrl();
        String newUrl = transformUrl(originalUrl, requestData.getServicename(), requestData.getNamespace());
        logger.info("原始 URL: {}，转换后的 URL: {}", originalUrl, newUrl);

        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setAll(requestData.getRequestDefine().getHeader());
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建HttpEntity
        HttpEntity<?> entity;
        if ("GET".equalsIgnoreCase(requestData.getRequestDefine().getMethod())) {
            entity = new HttpEntity<>(headers);
            logger.info("为 GET 请求创建 HttpEntity，包含请求头: {}", headers);
        } else {
            entity = new HttpEntity<>(requestData.getRequestDefine().getData(), headers);
            logger.info("为 {} 请求创建 HttpEntity，包含请求头: {} 和请求体: {}", requestData.getRequestDefine().getMethod(), headers, requestData.getRequestDefine().getData());
        }

        // 确定HttpMethod
        HttpMethod httpMethod = HttpMethod.resolve(requestData.getRequestDefine().getMethod().toUpperCase());
        logger.info("HTTP 方法: {}", httpMethod);

        // 发起HTTP请求
        ResponseEntity<String> response;
        try {
            response = restTemplate.exchange(newUrl, httpMethod, entity, String.class);
            logger.info("HTTP 请求到 {} 完成，状态码: {}", newUrl, response.getStatusCode());
        } catch (Exception e) {
            logger.error("HTTP 请求到 {} 期间发生错误: {}", newUrl, e.getMessage());
            responseData.setStatusCode(500);
            responseData.setBody(e.getMessage());
            return responseData;
        }
        responseData.setStatusCode(response.getStatusCode().value());
        responseData.setBody(response.getBody());
        return responseData;
    }

    private String transformUrl(String originalUrl, String servicename, String namespace) {
        // 如果 servicename 是 "front-end"，则不进行转换
        if ("front-end".equals(servicename)) {
            return originalUrl;
        }

        if (originalUrl.startsWith("http://")) {
            int firstSlashIndex = originalUrl.indexOf("/", "http://".length());
            if (firstSlashIndex != -1) {
                String suffix = originalUrl.substring(firstSlashIndex);
                String newBase = servicename + "." + namespace + ".svc.cluster.local";
                return "http://" + newBase + suffix;
            }
        }
        return originalUrl; // 如果不符合规则，则返回原始 URL
    }
}